package com.xinchao.ck_mips;

import android.content.Context;

import com.orhanobut.logger.Logger;

import com.xinchao.ck_mips.utils.DeviceInfoUtil;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.utils.SignUtil;

import com.xinchao.machine.digital_advertise.IBaseMachine;

import okhttp3.FormBody;

import okhttp3.Interceptor;

import okhttp3.Request;

import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @author: JessieKate
 * @date: 2018/10/22
 * @email: lyj1246505807@gmail.com
 * @description: 拦截器工具类
 */

public class InterceptorUtil {

    //日志拦截器
    public static HttpLoggingInterceptor LogInterceptor() {
        return new HttpLoggingInterceptor(message -> Logger.d("log: " + message)).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别
    }

    /**
     * 添加头部和公共参数拦截器
     *
     * @return
     */
    public static Interceptor AddHeaderParameterInterceptor(IBaseMachine iBaseMachine, Context mContext) {
        return chain -> {
            Request originalRequest = chain.request();
//          builder.addHeader("simIccid", simUtil.iccid);
//          builder.addHeader("simImei", simUtil.imei);
//          builder.addHeader("deviceNum", DeviceInfoUtil.getInstance().getDeviceId());
//          builder.addHeader("deviceCode", DeviceInfoUtil.getInstance().getDeviceId());
            // 拦截请求，添加公共参数
            FormBody.Builder newFormBody = new FormBody.Builder();
            // 如果老数据是表单格式，添加老数据
            if (originalRequest.body() instanceof FormBody) {
                FormBody oldFormBody = (FormBody) originalRequest.body();
                for (int i = 0; i < oldFormBody.size(); i++) {
                    newFormBody.addEncoded(oldFormBody.encodedName(i), oldFormBody.encodedValue(i));
                }
            }
            long curtime = System.currentTimeMillis();
            // 统一添加时间戳表单参数
            newFormBody.addEncoded("timestamp", String.valueOf(curtime));
            Request.Builder newRequestBuilder = originalRequest.newBuilder();
            // 统一添加header
            newRequestBuilder.addHeader("token", ShareUtil.getInstance().getToken());
            newRequestBuilder.addHeader("sign", SignUtil.getSign(originalRequest, curtime));
            // newRequestBuilder.addHeader("mac", NetWorkUtil.getMacAddressFromIp(mContext));
            newRequestBuilder.addHeader("mac", iBaseMachine.getLocalMac());
            newRequestBuilder.addHeader("networkingWay", DeviceUtil.getNetworkState(mContext));
            newRequestBuilder.addHeader("resolution", DeviceUtil.getResolution(mContext));
            newRequestBuilder.addHeader("devicecode", DeviceInfoUtil.getInstance().getDeviceCode());
            return chain.proceed(newRequestBuilder.post(newFormBody.build()).build());
        };
    }

}
